<template>
  <view class="payment-list-page">
    <!-- 搜索筛选 -->
    <view class="search-filter">
      <u-card :border="false">
        <view class="filter-row">
          <view class="filter-item">
            <u-input
              v-model="searchForm.keyword"
              placeholder="搜索订单号或费用类型"
              prefixIcon="search"
              clearable
              @change="handleSearch"
            ></u-input>
          </view>
          <view class="filter-item">
            <u-select
              v-model="searchForm.status"
              :list="statusOptions"
              placeholder="支付状态"
              @change="handleSearch"
            ></u-select>
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <u-input
              v-model="searchForm.startDate"
              placeholder="开始日期"
              readonly
              @click="showStartDatePicker = true"
            ></u-input>
          </view>
          <view class="filter-item">
            <u-input
              v-model="searchForm.endDate"
              placeholder="结束日期"
              readonly
              @click="showEndDatePicker = true"
            ></u-input>
          </view>
        </view>
      </u-card>
    </view>

    <!-- 支付记录列表 -->
    <view class="payment-list">
      <u-card 
        v-for="item in paymentList" 
        :key="item.id"
        :border="false"
        class="payment-item"
        @click="viewPaymentDetail(item)"
      >
        <view class="payment-header">
          <view class="payment-info">
            <text class="order-no">{{ item.orderNo }}</text>
            <text class="payment-status" :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</text>
          </view>
          <view class="payment-amount">
            <text class="amount">¥{{ item.amount }}</text>
          </view>
        </view>
        
        <view class="payment-detail">
          <view class="detail-row">
            <text class="detail-label">费用类型：</text>
            <text class="detail-value">{{ item.feeTypeName }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">支付方式：</text>
            <text class="detail-value">{{ item.paymentMethodName }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">支付时间：</text>
            <text class="detail-value">{{ item.paymentTime }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">房号：</text>
            <text class="detail-value">{{ item.roomNumber }}</text>
          </view>
        </view>
        
        <view class="payment-actions">
          <u-button 
            v-if="item.status === '2'"
            type="primary" 
            text="查看发票"
            size="mini"
            @click.stop="viewInvoice(item)"
          ></u-button>
          <u-button 
            v-if="item.status === '3'"
            type="warning" 
            text="重新支付"
            size="mini"
            @click.stop="retryPayment(item)"
          ></u-button>
          <u-button 
            type="default" 
            text="查看详情"
            size="mini"
            @click.stop="viewPaymentDetail(item)"
          ></u-button>
        </view>
      </u-card>
    </view>

    <!-- 空状态 -->
    <view v-if="paymentList.length === 0 && !loading" class="empty-state">
      <u-empty 
        text="暂无支付记录"
        icon="order"
      ></u-empty>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="load-more">
      <u-button 
        type="default" 
        text="加载更多"
        @click="loadMore"
      ></u-button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>

    <!-- 日期选择器 -->
    <u-picker
      :show="showStartDatePicker"
      mode="date"
      @confirm="handleStartDateChange"
      @cancel="showStartDatePicker = false"
    ></u-picker>
    
    <u-picker
      :show="showEndDatePicker"
      mode="date"
      @confirm="handleEndDateChange"
      @cancel="showEndDatePicker = false"
    ></u-picker>
  </view>
</template>

<script setup>
/**
 * 支付记录列表页面
 * @author Wu.Liang
 * @date 2025-01-27
 * @version 2.0 - 统一支付接口集成
 */

import { ref, reactive, onMounted } from 'vue'
import { unifiedPaymentApi } from '@/api/payment'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 状态选项
const statusOptions = ref([
  { label: '全部', value: '' },
  { label: '待支付', value: '0' },
  { label: '支付中', value: '1' },
  { label: '支付成功', value: '2' },
  { label: '支付失败', value: '3' },
  { label: '已退款', value: '4' }
])

// 支付列表
const paymentList = ref([])

// 分页参数
const pageParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)
const hasMore = ref(true)

// 日期选择器状态
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待支付',
    '1': '支付中',
    '2': '支付成功',
    '3': '支付失败',
    '4': '已退款',
    'success': '支付成功',
    'failed': '支付失败',
    'processing': '支付中',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    '0': 'pending',
    '1': 'processing',
    '2': 'success',
    '3': 'failed',
    '4': 'refunded'
  }
  return classMap[status] || 'unknown'
}

// 日期选择处理
const handleStartDateChange = (e) => {
  searchForm.startDate = e.value
  showStartDatePicker.value = false
  handleSearch()
}

const handleEndDateChange = (e) => {
  searchForm.endDate = e.value
  showEndDatePicker.value = false
  handleSearch()
}

// 搜索处理
const handleSearch = () => {
  pageParams.pageNum = 1
  hasMore.value = true
  loadPaymentList()
}

// 加载支付列表
const loadPaymentList = async (isLoadMore = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      userId: uni.getStorageSync('userId'),
      current: isLoadMore ? pageParams.pageNum + 1 : 1,
      size: pageParams.pageSize,
      ...searchForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await paymentApi.getPaymentPage(params)
    
    if (response.code === 200) {
      const { records, current, size, total, pages } = response.data
      
      if (isLoadMore) {
        paymentList.value.push(...records)
        pageParams.pageNum = current
      } else {
        paymentList.value = records
        pageParams.pageNum = 1
      }
      
      pageParams.total = total
      hasMore.value = current < pages
    } else {
      throw new Error(response.message || '获取支付记录失败')
    }
  } catch (error) {
    console.error('加载支付记录失败', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadPaymentList(true)
  }
}

// 查看支付详情
const viewPaymentDetail = (item) => {
  uni.navigateTo({
    url: `/pages/payment/detail?id=${item.id}`
  })
}

// 查看发票
const viewInvoice = (item) => {
  uni.navigateTo({
    url: `/pages/payment/invoice?orderNo=${item.orderNo}`
  })
}

// 重新支付
const retryPayment = (item) => {
  uni.navigateTo({
    url: `/pages/payment/payment?feeId=${item.businessOrderId}&amount=${item.amount}&feeType=${item.businessType}&roomNumber=${item.roomNumber}`
  })
}

// 页面加载时初始化数据
onMounted(() => {
  loadPaymentList()
})
</script>

<style lang="scss" scoped>
.payment-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
}

.search-filter {
  margin-bottom: 20px;
  
  .filter-row {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-item {
      flex: 1;
    }
  }
}

.payment-list {
  .payment-item {
    margin-bottom: 16px;
    
    .payment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .payment-info {
        .order-no {
          display: block;
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
        }
        
        .payment-status {
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 12px;
          
          &.pending {
            background-color: #e6f7ff;
            color: #1890ff;
          }
          
          &.processing {
            background-color: #fff7e6;
            color: #fa8c16;
          }
          
          &.success {
            background-color: #e6f7ff;
            color: #1890ff;
          }
          
          &.failed {
            background-color: #fff2f0;
            color: #ff4d4f;
          }
          
          &.refunded {
            background-color: #f5f5f5;
            color: #8c8c8c;
          }
        }
      }
      
      .payment-amount {
        .amount {
          font-size: 18px;
          font-weight: bold;
          color: #ff4757;
        }
      }
    }
    
    .payment-detail {
      margin-bottom: 12px;
      
      .detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .detail-label {
          font-size: 14px;
          color: #666;
        }
        
        .detail-value {
          font-size: 14px;
          color: #333;
        }
      }
    }
    
    .payment-actions {
      display: flex;
      gap: 8px;
      justify-content: flex-end;
    }
  }
}

.empty-state {
  padding: 60px 0;
}

.load-more {
  text-align: center;
  padding: 20px 0;
}

.loading {
  text-align: center;
  padding: 20px 0;
}
</style> 